package net.oschina.simpleplus.erpc.consumer;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.protobuf.InvalidProtocolBufferException;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import net.oschina.simpleplus.erpc.core.ERpcRequestEntity;

public class ERpcDecoder extends ByteToMessageDecoder{

	private static final Logger logger = LoggerFactory.getLogger(ERpcDecoder.class);
	
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		out.add(custDecodec(in));
	}

	private ERpcRequestEntity custDecodec(ByteBuf in) {
		ERpcRequestEntity eRpcRequestEntity = new ERpcRequestEntity();
		try {
			byte[] bs = new byte[in.readableBytes()];
			in.readBytes(bs, in.readerIndex(), in.readableBytes());
			eRpcRequestEntity.parseFrom(bs);
			logger.info("receive msg:{}", eRpcRequestEntity.getMsgId());
			return eRpcRequestEntity;
		} catch (InvalidProtocolBufferException e) {
			e.printStackTrace();
		}
		return null;
	}

}
